package com.bytz.modules.cms.reseller.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytz.common.constant.CommonConstant;
import com.bytz.common.system.api.ISysBaseApi;
import com.bytz.modules.cms.reseller.constant.ResellerConstant;
import com.bytz.modules.cms.reseller.entity.Reseller;
import com.bytz.modules.cms.reseller.mapper.ResellerMapper;
import com.bytz.modules.cms.reseller.service.IResellerLevelService;
import com.bytz.modules.cms.reseller.service.IResellerService;
import com.bytz.modules.system.security.vo.LoginReseller;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 莱宝CMS—经销商管理—经销商基本信息表 服务实现类
 * </p>
 *
 * @author KyleWang
 * @since 2022-10-10
 */
@Service
public class ResellerServiceImpl extends ServiceImpl<ResellerMapper, Reseller> implements IResellerService {

    @Autowired
    private ISysBaseApi sysBaseApi;

    @Autowired
    private IResellerLevelService resellerLevelService;

    @Override
    @Cacheable(cacheNames = ResellerConstant.ResellerSecurity.CACHE_PREFIX, key = "#username")
    public LoginReseller getForLogin(String username) {
        Optional<Reseller> reseller = lambdaQuery().eq(Reseller::getUsername, username).oneOpt();

        return reseller.map(p -> BeanUtil.toBean(p, LoginReseller.class)).orElse(null);
    }

    @Override
    public boolean checkReseller(LoginReseller user, String username, boolean log) {
        //情况1：根据用户信息查询，该用户不存在
        if (user == null) {
            if (log) {
                sysBaseApi.addLog("用户登录失败，经销商【" + username + "】不存在！", CommonConstant.LOG_TYPE_1, null);
            }

            return false;
        }

        //情况2：根据用户信息查询，该用户已注销
        if (CommonConstant.DEL_FLAG_1.equals(user.getDelFlag())) {
            if (log) {
                sysBaseApi.addLog("用户登录失败，用户名:" + user.getUsername() + "已注销！", CommonConstant.LOG_TYPE_1, null);
            }

            // 安全上不应提供详细错误
            return false;
        }
        //情况3：根据用户信息查询，该用户已冻结
        if (CommonConstant.USER_FREEZE.equals(user.getStatus())) {
            if (log) {
                sysBaseApi.addLog("用户登录失败，用户名:" + user.getUsername() + "已冻结！", CommonConstant.LOG_TYPE_1, null);
            }

            // 安全上不应提供详细错误
            return false;
        }

        return true;
    }

    @Override
    public List<Reseller> getByNames(Collection<String> resellerNames) {

        if (CollectionUtil.isEmpty(resellerNames)) {
            return new ArrayList<>();
        }

        return lambdaQuery()
                .in(Reseller::getResellerName, resellerNames)
                .list();
    }

    @Override
    @CacheEvict(cacheNames = {ResellerConstant.ResellerSecurity.SECURITY_CACHE_PREFIX, ResellerConstant.ResellerSecurity.CACHE_PREFIX}, key = "#username")
    public boolean updatePassword(String id, String username, String password) {
        return lambdaUpdate()
                .eq(Reseller::getId, id)
                .set(Reseller::getPassword, password)
                .update();
    }

    @Override
    public void resetLevels(String id) {
        List<String> levelNames = resellerLevelService.getLevelNameByResellerId(id);
        lambdaUpdate()
                .eq(Reseller::getId, id)
                .set(Reseller::getLevels, StrUtil.join("、", levelNames))
                .update();
    }

    @Override
    public Boolean needPaymentPassword(String userId) {
        return StringUtils.isNotBlank(getById(userId).getPaymentPassword());
    }
}
